<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>Product Management - CarbonTrack</title>
  <link rel="icon" href="/img/team.jpg" type="image/JPG">
  <link rel="stylesheet" href="./css/bootstrap.min.css">
  <script src="./js/jquery.min.js"></script>
  <script src="https://cdn.staticfile.org/twitter-bootstrap/4.5.2/js/bootstrap.min.js"></script>
  <script src="js/utils.js"></script>
  <script src="js/nav.js"></script>
  <!-- SF Pro 字体 -->
  <link href="https://fonts.cdnfonts.com/css/sf-pro-display" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
  <!-- Intersection Observer polyfill -->
  <script src="https://cdn.jsdelivr.net/npm/intersection-observer@0.12.2/intersection-observer.js"></script>
  <!-- iOS设计CSS -->
  <link rel="stylesheet" href="./css/ios-design.css">
  <link rel="stylesheet" href="./css/index.css">
  <style>
    .admin-header {
      background: linear-gradient(135deg, var(--ios-orange), var(--ios-pink));
      color: white;
      padding: 120px 0 60px;
      text-align: center;
      border-radius: 0 0 24px 24px;
      margin-bottom: 40px;
    }
    
    .admin-header h1 {
      font-weight: 700;
      margin-bottom: 16px;
    }
    
    .admin-header p {
      opacity: 0.9;
      max-width: 600px;
      margin: 0 auto;
      font-size: 1.1rem;
    }
    
    .admin-card {
      border-radius: 24px;
      overflow: hidden;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
      margin-bottom: 30px;
      transition: transform 0.4s var(--animation-timing-apple),
                  box-shadow 0.4s var(--animation-timing-apple);
      background-color: var(--ios-system-background);
    }
    
    .admin-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 16px 40px rgba(0, 0, 0, 0.1);
    }
    
    .product-card {
      border-radius: 24px;
      overflow: hidden;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
      margin-bottom: 30px;
      transition: transform 0.4s var(--animation-timing-apple),
                  box-shadow 0.4s var(--animation-timing-apple);
      height: 100%;
      background-color: var(--ios-system-background);
    }
    
    .product-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 16px 40px rgba(0, 0, 0, 0.1);
    }
    
    .product-img {
      width: 100%;
      height: 200px;
      object-fit: cover;
    }
    
    .product-body {
      padding: 24px;
    }
    
    .product-title {
      font-weight: 700;
      margin-bottom: 8px;
      font-size: 1.2rem;
    }
    
    .product-detail {
      color: var(--ios-gray);
      margin-bottom: 4px;
      font-size: 0.95rem;
    }
    
    .product-price {
      font-weight: 700;
      color: var(--ios-green);
      margin-bottom: 4px;
    }
    
    .section-title {
      font-weight: 700;
      margin-bottom: 24px;
      position: relative;
      padding-bottom: 12px;
    }
    
    .section-title::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 60px;
      height: 4px;
      background: linear-gradient(to right, var(--ios-orange), var(--ios-pink));
      border-radius: 2px;
    }
    
    .form-card {
      background: var(--ios-system-background);
      border-radius: 24px;
      padding: 24px;
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);
      margin-bottom: 30px;
    }
    
    .form-group label {
      font-weight: 600;
      margin-bottom: 8px;
      color: var(--ios-label);
    }
    
    .form-control {
      border-radius: 12px;
      border: 1px solid var(--ios-gray-light);
      padding: 12px 16px;
      transition: all 0.3s var(--animation-timing-apple);
    }
    
    .form-control:focus {
      border-color: var(--ios-blue);
      box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.2);
    }
    
    .btn-add {
      background: linear-gradient(135deg, var(--ios-green), var(--ios-teal));
      color: white;
      border: none;
      border-radius: 12px;
      padding: 12px 24px;
      font-weight: 600;
      transition: all 0.3s var(--animation-timing-apple);
      box-shadow: 0 6px 16px rgba(46, 204, 113, 0.15);
    }
    
    .btn-add:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 24px rgba(46, 204, 113, 0.25);
    }
    
    .btn-update {
      background: linear-gradient(135deg, var(--ios-blue), var(--ios-indigo));
      color: white;
      border: none;
      border-radius: 12px;
      padding: 12px 24px;
      font-weight: 600;
      transition: all 0.3s var(--animation-timing-apple);
      box-shadow: 0 6px 16px rgba(0, 122, 255, 0.15);
    }
    
    .btn-update:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 24px rgba(0, 122, 255, 0.25);
    }
    
    .btn-delete {
      background: linear-gradient(135deg, var(--ios-red), var(--ios-pink));
      color: white;
      border: none;
      border-radius: 12px;
      padding: 12px 24px;
      font-weight: 600;
      transition: all 0.3s var(--animation-timing-apple);
      box-shadow: 0 6px 16px rgba(231, 76, 60, 0.15);
    }
    
    .btn-delete:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 24px rgba(231, 76, 60, 0.25);
    }
  </style>
</head>
<body>

<!-- Theme Toggle Button -->
<button id="theme-toggle-button" aria-label="Toggle theme" class="ios-theme-toggle-btn">
  <i class="fas fa-sun"></i> <!-- Default icon -->
</button>

<!-- 导航栏容器，将由JavaScript加载 -->
<div id="navbar-container"></div>

<header class="admin-header">
  <div class="container">
    <h1>Product Management</h1>
    <p>Add, update, and manage products in the Carbon Credits Mall</p>
  </div>
</header>

<div class="container">
  <div class="row">
    <div class="col-md-6">
      <div class="form-card ios-depth-effect">
        <h2 class="section-title">Add New Product</h2>
        <form id="addProductForm">
          <div class="form-group">
            <label for="addName"><i class="fas fa-tag mr-2"></i>Product Name:</label>
            <input type="text" class="form-control" id="addName" required>
          </div>
          <div class="form-group">
            <label for="addDescription"><i class="fas fa-info-circle mr-2"></i>Description:</label>
            <textarea class="form-control" id="addDescription" rows="3" required></textarea>
          </div>
          <div class="form-group">
            <label for="addPrice"><i class="fas fa-coins mr-2"></i>Price (Credits):</label>
            <input type="number" class="form-control" id="addPrice" required>
          </div>
          <div class="form-group">
            <label for="addStock"><i class="fas fa-warehouse mr-2"></i>Stock Quantity:</label>
            <input type="number" class="form-control" id="addStock" required>
          </div>
          <button type="submit" class="btn btn-add btn-block">
            <i class="fas fa-plus-circle mr-2"></i>Add Product
          </button>
        </form>
      </div>
    </div>
    <div class="col-md-6">
      <div class="form-card ios-depth-effect">
        <h2 class="section-title">Update or Delete Product</h2>
        <form id="updateDeleteProductForm">
          <div class="form-group">
            <label for="updateProductId"><i class="fas fa-fingerprint mr-2"></i>Product ID:</label>
            <input type="number" class="form-control" id="updateProductId" required>
          </div>
          <div class="form-group">
            <label for="updateName"><i class="fas fa-tag mr-2"></i>Product Name:</label>
            <input type="text" class="form-control" id="updateName" required>
          </div>
          <div class="form-group">
            <label for="updateDescription"><i class="fas fa-info-circle mr-2"></i>Description:</label>
            <textarea class="form-control" id="updateDescription" rows="3" required></textarea>
          </div>
          <div class="form-group">
            <label for="updatePrice"><i class="fas fa-coins mr-2"></i>Price (Credits):</label>
            <input type="number" class="form-control" id="updatePrice" required>
          </div>
          <div class="form-row">
            <div class="col-md-6">
              <button type="button" class="btn btn-update btn-block" onclick="updateProduct()">
                <i class="fas fa-sync-alt mr-2"></i>Update
              </button>
            </div>
            <div class="col-md-6">
              <button type="button" class="btn btn-delete btn-block" onclick="deleteProduct()">
                <i class="fas fa-trash-alt mr-2"></i>Delete
              </button>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<div class="container mt-4">
  <h2 class="section-title">Current Products</h2>

  <!-- Search Bar -->
  <div class="row mb-3">
    <div class="col-md-6">
      <div class="input-group">
        <input type="text" id="productSearchInput" class="form-control" placeholder="Search by Product Name...">
        <div class="input-group-append">
          <button class="btn btn-primary" type="button" id="productSearchButton">Search</button>
          <button class="btn btn-secondary" type="button" id="clearProductSearchButton">Clear</button>
        </div>
      </div>
    </div>
  </div>

  <div id="productList" class="row">
    <!-- Product list or loading indicator -->
  </div>
  <!-- Pagination Controls -->
  <div id="pagination-controls" class="mt-4 text-center"></div>
</div>

<script>
  var currentPage = 1;
  var productsPerPage = 12; 
  var totalProducts = 0;
  var currentSearchTerm = null; // For product search

  // Theme toggling logic (Add this block)
  const themeToggleButton = document.getElementById('theme-toggle-button');
  const currentTheme = localStorage.getItem('theme') || 'auto'; // Default to 'auto'

  function applyTheme(theme) {
    const body = document.body;
    const icon = themeToggleButton.querySelector('i');
    body.classList.remove('light-theme', 'dark-theme'); // Remove existing theme classes

    let isDark = false;
    if (theme === 'dark' || (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
      body.classList.add('dark-theme');
      icon.className = 'fas fa-moon'; // Moon icon for dark
      isDark = true;
    } else {
      body.classList.add('light-theme'); // Explicitly add light-theme or rely on default
      icon.className = 'fas fa-sun'; // Sun icon for light
      isDark = false;
    }
    localStorage.setItem('theme', theme);

     // Update icon for auto based on effective theme
    if (theme === 'auto') {
       icon.className = 'fas fa-adjust'; // Use adjust icon for auto
    }
    
    // --- Add specific component updates for dark/light mode if needed --- 
    // Example: Update form controls based on theme (might already be handled by CSS variables)
    document.querySelectorAll('.form-control').forEach(el => {
        if (isDark) {
            // Add dark mode specific classes or styles if not handled by CSS vars
            // e.g., el.classList.add('form-control-dark'); 
        } else {
            // Remove dark mode specific classes or styles
             // e.g., el.classList.remove('form-control-dark');
        }
    });
      // Example: Update modal styles if any modals exist
    document.querySelectorAll('.modal-content').forEach(el => {
        if (isDark) {
            el.classList.add('bg-dark', 'text-light'); // Bootstrap dark mode for modals
        } else {
            el.classList.remove('bg-dark', 'text-light');
        }
    });
    
  }

  function cycleTheme() {
    const themes = ['light', 'dark', 'auto'];
    let currentThemeIndex = themes.indexOf(localStorage.getItem('theme') || 'auto');
    let nextThemeIndex = (currentThemeIndex + 1) % themes.length;
    applyTheme(themes[nextThemeIndex]);
  }

  // Apply initial theme on load
  applyTheme(currentTheme);

  // Listen for system theme changes if in 'auto' mode
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
    if (localStorage.getItem('theme') === 'auto') {
      applyTheme('auto');
    }
  });

  // Add event listener to the button
  themeToggleButton.addEventListener('click', cycleTheme);

  $(document).ready(function () {
    var token = localStorage.getItem('token'); 
    if (!token) {
      showAlert('请先登录！', 'warning', function() {
        window.location.href = 'index.html'; 
      });
      return;
    }
    
    verifyAdmin(); 

    // Product Search button click
    $('#productSearchButton').on('click', function() {
      currentSearchTerm = $('#productSearchInput').val();
      fetchProducts(1, currentSearchTerm); // Reset to page 1 on new search
    });

    // Clear Product Search button click
    $('#clearProductSearchButton').on('click', function() {
      $('#productSearchInput').val('');
      currentSearchTerm = null;
      fetchProducts(1, currentSearchTerm); // Reset to page 1 and clear search
    });

    // Optional: Trigger product search on Enter key press
    $('#productSearchInput').on('keypress', function(e) {
      if (e.which == 13) { // Enter key pressed
        $('#productSearchButton').click(); 
      }
    });
  });

  function verifyAdmin() {
    var token = localStorage.getItem('token');
    $.ajax({
      type: 'POST',
      data: { token: token },
      url: 'verify_admin.php',
      dataType: 'json',
      success: function (response) {
        if (response.success && response.isAdmin) {
          fetchProducts(currentPage, currentSearchTerm); // Initial fetch
          setupForms(); 
        } else {
          showAlert('访问被拒绝。您不是管理员。', 'error', function() {
            window.location.href = 'index.html';
          });
        }
      },
      error: function () {
        showAlert('验证失败，请重试。', 'error', function() {
          window.location.href = 'index.html';
        });
      },
    });
  }

  // Separate function to setup form handlers, called after admin verification
  function setupForms() {
      $('#addProductForm').submit(function (e) {
        e.preventDefault();
        
        var submitBtn = $(this).find('button[type="submit"]');
        var originalText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin mr-2"></i> Adding...');
        submitBtn.prop('disabled', true);
        
        var name = $('#addName').val();
        var description = $('#addDescription').val();
        var price = $('#addPrice').val();
        var stock = $('#addStock').val();
        var token = localStorage.getItem('token');
        
        $.ajax({
          type: 'POST',
          url: 'add_product.php',
          data: {
            name: name,
            description: description,
            points_required: price,
            stock: stock,
            token: token, // Token is required for adding
          },
          success: function (response) {
            submitBtn.html(originalText);
            submitBtn.prop('disabled', false);
            
            if (response.success) {
              showAlert('商品添加成功！', 'success', function() {
                $('#addProductForm')[0].reset();
                fetchProducts(1, currentSearchTerm); // Go to first page to see newly added product
              });
            } else {
              showAlert('添加商品失败：' + response.message, 'error');
            }
          },
          error: function (xhr) {
            submitBtn.html(originalText);
            submitBtn.prop('disabled', false);
            showAlert('请求失败，请重试：' + xhr.responseText, 'error');
          },
        });
      });
      // Note: updateProduct and deleteProduct are called via onclick, no need to setup submit here
  }

  function updateProduct() {
    var submitBtn = $('.btn-update');
    var originalText = submitBtn.html();
    submitBtn.html('<i class="fas fa-spinner fa-spin mr-2"></i> Updating...');
    submitBtn.prop('disabled', true);
    
    var productId = $('#updateProductId').val();
    var name = $('#updateName').val();
    var description = $('#updateDescription').val();
    var price = $('#updatePrice').val();
    var token = localStorage.getItem('token');
    
    $.ajax({
      type: 'POST',
      url: 'update_product.php',
      data: {
        product_id: productId,
        name: name,
        description: description,
        price: price,
        token: token,
      },
      success: function (response) {
        submitBtn.html(originalText);
        submitBtn.prop('disabled', false);
        
        if (response.success) {
          showAlert('商品更新成功！', 'success', function() {
            fetchProducts(currentPage, currentSearchTerm); // Refresh current page
          });
        } else {
          showAlert('更新商品失败：' + response.message, 'error');
        }
      },
      error: function (xhr) {
        submitBtn.html(originalText);
        submitBtn.prop('disabled', false);
        showAlert('请求失败，请重试。', 'error');
      },
    });
  }

  function deleteProduct() {
    if (!confirm('Are you sure you want to delete this product? This action cannot be undone.')) {
      return;
    }
    
    var submitBtn = $('.btn-delete');
    var originalText = submitBtn.html();
    submitBtn.html('<i class="fas fa-spinner fa-spin mr-2"></i> Deleting...');
    submitBtn.prop('disabled', true);
    
    var productId = $('#updateProductId').val();
    var token = localStorage.getItem('token');
    
    $.ajax({
      type: 'POST',
      url: 'delete_product.php',
      data: {
        product_id: productId,
        token: token,
      },
      success: function (response) {
        submitBtn.html(originalText);
        submitBtn.prop('disabled', false);
        
        if (response.success) {
          showAlert('商品删除成功！', 'success', function() {
            $('#updateDeleteProductForm')[0].reset();
            fetchProducts(currentPage, currentSearchTerm); // Refresh current page, might need to go to previous if last item deleted
            // TODO: Add logic to go to previous page if current page becomes empty after delete
          });
        } else {
          showAlert('删除商品失败：' + response.message, 'error');
        }
      },
      error: function (xhr) {
        submitBtn.html(originalText);
        submitBtn.prop('disabled', false);
        showAlert('请求失败，请重试。', 'error');
      },
    });
  }

  function fetchProducts(page, searchTerm) {
    currentPage = page;
    currentSearchTerm = searchTerm;
    var productList = $('#productList');
    var paginationControls = $('#pagination-controls');
    productList.html('<div class="col-12 text-center py-5"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div><p class="mt-3">Loading products...</p></div>');
    paginationControls.empty();

    var requestData = { 
        page: currentPage, 
        limit: productsPerPage 
    };
    if (currentSearchTerm && currentSearchTerm.trim() !== '') {
        requestData.searchTerm = currentSearchTerm;
    } else {
        currentSearchTerm = null; // Ensure consistency
    }

    $.ajax({
      type: 'GET',
      url: 'product.php',
      data: requestData, // Pass pagination & search params
      dataType: 'json',
      success: function (response) {
        productList.empty();
        if (response.success) {
          totalProducts = response.total;
          currentPage = response.page;
          productsPerPage = response.limit;
          $('#productSearchInput').val(response.searchTerm || ''); // Update search box
          
          renderProducts(response.products);
          
          // Display message if no products found
          if (response.products.length === 0) {
              let message = totalProducts === 0 ? 'No products available. Add your first product!' : 'No matching products found.';
              if (currentSearchTerm) {
                  message = `No products found matching "${currentSearchTerm}".`;
              }
              productList.html(`<div class="col-12 text-center py-5"><p>${message}</p></div>`);
          }
          
          renderPaginationControls();
        } else {
          console.error('Failed to get products: ' + response.message);
          productList.html('<div class="col-12"><div class="alert alert-danger">Failed to load products: ' + response.message + '</div></div>');
        }
      },
      error: function () {
        productList.empty();
        console.error('Product data request failed.');
        productList.html('<div class="col-12"><div class="alert alert-danger">Failed to load products. Please try again later.</div></div>');
      },
    });
  }

 function renderPaginationControls() {
    const paginationContainer = $('#pagination-controls');
    paginationContainer.empty();
    
    if (totalProducts === 0) return; 

    const totalPages = Math.ceil(totalProducts / productsPerPage);

    if (totalPages <= 1) return; 

    let paginationHTML = '<nav aria-label="Product page navigation"><ul class="pagination justify-content-center">';

    // Previous button (includes search term)
    paginationHTML += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                         <a class="page-link" href="#" onclick="fetchProducts(${currentPage - 1}, currentSearchTerm)">Previous</a>
                       </li>`;

    // Page numbers (simplified)
    paginationHTML += `<li class="page-item disabled"><span class="page-link">Page ${currentPage} of ${totalPages}</span></li>`; 

    // Next button (includes search term)
    paginationHTML += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                         <a class="page-link" href="#" onclick="fetchProducts(${currentPage + 1}, currentSearchTerm)">Next</a>
                       </li>`;

    paginationHTML += '</ul></nav>';
    paginationContainer.html(paginationHTML);
 }

  function renderProducts(products) {
    var productList = $('#productList');
    productList.empty(); // Clear existing product list
    
    if (products.length === 0) {
      productList.html('<div class="col-12 text-center py-5"><p>No products available. Add your first product!</p></div>');
      return;
    }
    
    products.forEach(function (product) {
      var productHTML = `
      <div class="col-md-4 mb-4">
        <div class="product-card ios-hover-effect">
          <img class="product-img" src="${product.image_path || '/img/placeholder.jpg'}" alt="${product.name}">
          <div class="product-body">
            <h3 class="product-title">${product.name}</h3>
            <p class="product-detail"><strong>ID:</strong> ${product.product_id}</p>
            <p class="product-detail">${product.description}</p>
            <p class="product-price">${product.price} Credits</p>
            <p class="product-detail"><strong>Stock:</strong> ${product.stock}</p>
            <button class="btn btn-update btn-sm" onclick="fillUpdateForm(${product.product_id}, '${product.name}', '${product.description}', ${product.price})">
              <i class="fas fa-edit mr-1"></i> Edit
            </button>
          </div>
        </div>
      </div>`;
      productList.append(productHTML);
    });
  }
  
  function fillUpdateForm(id, name, description, price) {
    $('#updateProductId').val(id);
    $('#updateName').val(name);
    $('#updateDescription').val(description);
    $('#updatePrice').val(price);
    
    // Scroll to the update form
    $('html, body').animate({
      scrollTop: $('#updateDeleteProductForm').offset().top - 100
    }, 800);
  }
</script>

<!-- 页脚 -->
<div id="footer-placeholder"></div>
</body>
</html>
